package org.stvd.core.process;

import java.io.IOException;

import org.stvd.core.util.DateUtil;
import org.stvd.core.web.IOUtil;

public class ProcessBatchThread extends Thread {

    /* cmd /c dir */
    private final String command;
    private String message = "";
    private final String filename;
    private final String filepath;

    /* 外部对象信息 */
    private Object infoObj;

    public Object getInfoObj() {
        return infoObj;
    }

    public void setInfoObj(Object infoObj) {
        this.infoObj = infoObj;
    }

    public ProcessBatchThread(String command) {
        // 日志文件和目录
        this.filepath = Thread.currentThread().getContextClassLoader().getResource(".././").getPath()
                + "/scheduler/logs/system/";
        this.filename = DateUtil.getSystemDateString() + ".txt";
        IOUtil.mkdir(filepath);
        this.command = command;
    }

    public ProcessBatchThread(String command, String filepath, String filename) {
        this.command = command;
        this.filepath = filepath;
        this.filename = filename;
    }

    public void run() {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder();
            processBuilder.command(command.split(" "));
            Process process = processBuilder.start();

            InputStreamWatchThread inputStreamWatchThread = new InputStreamWatchThread(process, filepath, filename);
            inputStreamWatchThread.start();

            ErrorInputStreamWatchThread errorInputStreamWatchThread = new ErrorInputStreamWatchThread(process, filepath,
                    filename);
            errorInputStreamWatchThread.start();

            process.waitFor();
            inputStreamWatchThread.setOver(true);
            errorInputStreamWatchThread.setOver(true);
        } catch (IOException e) {
            message += e.getMessage();
        } catch (InterruptedException e) {
            message += e.getMessage();
            Thread.currentThread().interrupt();
        }

        try {
            if (!"".equals(message.trim()) && !"".equals(filepath) && !"".equals(filename)) {
                IOUtil.saveFile(filepath, filename, message, true);
            }
        } catch (Exception e) {
        }
    }

//    public static void main(String[] args) throws IOException {
//        ProcessBatchThread batch = new ProcessBatchThread("cmd /c list");
//        batch.start();
//    }
}